package com.atguigu.netty.mqtt;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.DecoderResult;
import io.netty.handler.codec.mqtt.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.UUID;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 * 说明
 * 1、自定义handler需要继承netty规定好某个HandlerAdapter
 */
public class NettyMqttClientHandler extends SimpleChannelInboundHandler<MqttMessage> {

    private Logger logger = LoggerFactory.getLogger(NettyMqttClientHandler.class);

    private int reconnect = 0;

    /**
     * 通道就绪时触发
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("client " + ctx.channel().remoteAddress() + " active");
        //连接
        MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.CONNECT, false, MqttQoS.AT_MOST_ONCE, false, 0);
        MqttConnectVariableHeader mqttConnectVariableHeader = new MqttConnectVariableHeader(MqttVersion.MQTT_3_1_1.protocolName(), MqttVersion.MQTT_3_1_1.protocolLevel(), true, true, false, 0, false, false, 60);
        MqttConnectPayload mqttConnectPayload = new MqttConnectPayload(UUID.randomUUID().toString(), "pckj_djj/+", null, "admin", "root.inspur".getBytes());
        MqttMessage mqttMessage = MqttMessageFactory.newMessage(mqttFixedHeader, mqttConnectVariableHeader, mqttConnectPayload);

        ctx.writeAndFlush(mqttMessage, ctx.newPromise().addListener((future) -> {
            if (future.cause() == null) {
                logger.info("send connectMessage success");
            } else {
                logger.error("send connectMessage error " + future.cause());
            }
        }));

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("断开连接");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MqttMessage msg) throws Exception {

        logger.info("当前线程：{}",Thread.currentThread().getName());

        DecoderResult decoderResult = msg.decoderResult();

        MqttMessageType mqttMessageType = msg.fixedHeader().messageType();
        switch (mqttMessageType) {
            case CONNACK:
                processConnectAckResp(ctx, msg);
                break;
            case SUBACK:
                if (decoderResult.isSuccess()) {
                    logger.info("主题订阅成功");
                } else {
                    logger.error("主题订阅失败");
                }
                break;
            case PUBLISH:
                MqttPublishMessage mqttPublishMessage = (MqttPublishMessage) msg;
                if (decoderResult.isSuccess()) {
                    ByteBuf byteBuf = mqttPublishMessage.payload();
                    byte[] bytes = new byte[byteBuf.readableBytes()];
                    byteBuf.readBytes(bytes);
                    logger.info("接收消息:{}", new String(bytes));
                }
                break;
            default:
                logger.info("未处理消息 message type " + mqttMessageType);
                break;
        }
    }


    /**
     * 异常处理，通常关闭通道
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.error("异常", cause);
        ctx.close();
    }


    private void processConnectAckResp(ChannelHandlerContext ctx, MqttMessage msg) {
        if (msg.decoderResult().isSuccess()) {

            logger.info("get connectAck success, start heart beat");

            MqttFixedHeader mqttFixedHeader = new MqttFixedHeader(MqttMessageType.SUBSCRIBE, false, MqttQoS.AT_MOST_ONCE, false, 0);
            MqttMessageIdVariableHeader mqttMessageIdVariableHeader = MqttMessageIdVariableHeader.from(1);
            MqttTopicSubscription mqttTopicSubscription = new MqttTopicSubscription("pckj_djj/+", MqttQoS.AT_MOST_ONCE);
            MqttSubscribePayload mqttSubscribePayload = new MqttSubscribePayload(Collections.singletonList(mqttTopicSubscription));
            MqttMessage mqttMessage = MqttMessageFactory.newMessage(mqttFixedHeader, mqttMessageIdVariableHeader, mqttSubscribePayload);
            ctx.writeAndFlush(mqttMessage, ctx.newPromise().addListener((future) -> {
                if (future.cause() == null) {
                    logger.info("send SubscribMessage success");
                } else {
                    logger.error("send SubscribMessage error ", future.cause());
                }
            }));

            //存
//            ctx.channel().attr(MyConstants.pingKey).setIfAbsent("firstPing");
            // 定时心跳任务
            ctx.channel().eventLoop().scheduleAtFixedRate(() -> {
                MqttMessage pingmqttMessage = MqttMessageFactory.newMessage(new MqttFixedHeader(MqttMessageType.PINGREQ, false, MqttQoS.AT_MOST_ONCE, false, 0), null, null);
                ctx.writeAndFlush(pingmqttMessage, ctx.newPromise().addListener((future) -> {
                    if (future.cause() == null) {
                        logger.info("send heartBeat success");
                    } else {
                        logger.error("send heartBeat error");
                    }
                }));
            }, 2, 60, SECONDS);
        } else  {
            logger.error("get connectAck failed, cannot heart beat,username or password");//
            ctx.close();
        }
    }
}
